package com.lalawaimai.plateform.order.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lalawaimai.palteform.baselib.base.BaseFragment;
import com.lalawaimai.palteform.baselib.http.CommonBean;
import com.lalawaimai.palteform.baselib.http.DisposeDataListener;
import com.lalawaimai.palteform.baselib.http.OkHttpException;
import com.lalawaimai.palteform.baselib.http.RequestWebInfo;
import com.lalawaimai.palteform.baselib.utils.CommonUtil;
import com.lalawaimai.palteform.baselib.utils.NullUtil;
import com.lalawaimai.plateform.R;
import com.lalawaimai.plateform.bean.DeliveryerBean;
import com.lalawaimai.plateform.bean.DispatchBean;
import com.lalawaimai.plateform.bean.OrderListBean;
import com.lalawaimai.plateform.bean.OrderListEntity;
import com.lalawaimai.plateform.constant.Constant;
import com.lalawaimai.plateform.home.HomeActivity;
import com.lalawaimai.plateform.http.WebUrl;
import com.lalawaimai.plateform.order.activity.CancelReasonActivity;
import com.lalawaimai.plateform.order.activity.DispatchMapActivity;
import com.lalawaimai.plateform.order.adapter.WaitOrderAdapter;
import com.lalawaimai.plateform.order.activity.OrderDetailActivity;
import com.lalawaimai.plateform.order.inter.IButtonRequest;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单列表内页
 * Created by WaterWood on 2018/5/30.
 */
public class WaitOrderFragment extends BaseFragment implements IButtonRequest {

    private int flag;//各个内页区分
    private ListView lv_order;
    private WaitOrderAdapter waitOrderAdapter;
    private SmartRefreshLayout refreshLayout;
    private int page = 1;
    private String status;
    private List<OrderListEntity> list_order;//列表中的内容
    private final int MAX_PAGE = 20;//每页最大数量
    private ProgressDialog dialogWeb;//网络加载等待框
    public static final int CANCEL_REASON = 1;//点击取消返回
    public static final int REFRESH_LAYOUT = 2;//返回后刷新列表
    public static final int JUMP_MAP = 3;//调度返回识别码
    private HomeActivity homeActivity;
    private RelativeLayout rl_empty;
    private TextView tv_empty;
    private OrderListEntity orderNeedDelete;//1.调度进入的时候是哪一项  2.取消订单的相关

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_wait_order;
    }

    @Override
    protected void initArgs(Bundle bundle) {
        flag = bundle.getInt("flag", 0);
        if (flag == 1) {
            status = "1";
        } else if (flag == 2) {
            status = "2";
        } else if (flag == 3) {
            status = "3";
        } else if (flag == 4) {
            status = "4";
        } else if (flag == 5) {
            status = "7";
        }
    }

    @Override
    protected void initWidget(View root) {
        homeActivity = (HomeActivity) getActivity();
        //初始化控件
        lv_order = root.findViewById(R.id.lv_order);
        refreshLayout = root.findViewById(R.id.refreshLayout);
        rl_empty = root.findViewById(R.id.rl_empty);
        tv_empty = root.findViewById(R.id.tv_empty);
        //初始化布局
        list_order = new ArrayList<>();
        waitOrderAdapter = new WaitOrderAdapter(getActivity(), list_order);
        waitOrderAdapter.setType(status);
        waitOrderAdapter.setiButtonRequest(this);
        lv_order.setAdapter(waitOrderAdapter);
        lv_order.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
                intent.putExtra("id", list_order.get(position).getId());
                intent.putExtra("status", status);
                startActivityForResult(intent,REFRESH_LAYOUT);
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getOrderList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getOrderList();
            }
        });
        dialogWeb = CommonUtil.showProgressDialog(getActivity(), "正在加载");
        tv_empty.setText("没有相关订单");
    }

    @Override
    protected void initData() {
        refreshLayout.autoRefresh();
    }

    private void getOrderList() {
        String url = WebUrl.GET_ORDER_LIST;
        Class<?> clazz = OrderListBean.class;
        List<String> list = new ArrayList<>();
        list.add("status");
        list.add("page");
        list.add("token");
        new RequestWebInfo(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                OrderListBean orderListBean = (OrderListBean) responseObj;
                if (page == 1) {
                    refreshLayout.finishRefresh();
                    //刷新操作
                    List<OrderListEntity> list = orderListBean.getMessage().getData().getOrder();
                    list_order.clear();
                    if (!NullUtil.isListEmpty(list)) {
                        //有东西
                        list_order.addAll(list);
                        //如果第一页就小于二十条，直接禁止加载更多
                        if (list.size() < MAX_PAGE) {
                            refreshLayout.setEnableLoadMore(false);
                        } else {
                            if (!refreshLayout.isEnableLoadMore()) {
                                refreshLayout.setEnableLoadMore(true);
                            }
                        }
                        rl_empty.setVisibility(View.GONE);
                    } else {
                        //没有东西，显示空页面，隐藏列表
                        rl_empty.setVisibility(View.VISIBLE);
                    }
                    waitOrderAdapter.notifyDataSetChanged();
                } else {
                    //加载更多
                    refreshLayout.finishLoadMore();
                    List<OrderListEntity> list = orderListBean.getMessage().getData().getOrder();
                    if (!NullUtil.isListEmpty(list)) {
                        //有东西
                        list_order.addAll(list);
                        //如果这一页小于这么多，直接禁止加载更多
                        if (list.size() < MAX_PAGE) {
                            refreshLayout.setEnableLoadMore(false);
                        } else {
                            if (!refreshLayout.isEnableLoadMore()) {
                                refreshLayout.setEnableLoadMore(true);
                            }
                        }
                        waitOrderAdapter.notifyDataSetChanged();
                        rl_empty.setVisibility(View.GONE);
                    } else {
                        //没东西
                        CommonUtil.showToast(getActivity(), "已经加载到底了");
                        refreshLayout.setEnableLoadMore(false);
                    }
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                OkHttpException okHttpException = (OkHttpException) reasonObj;
                String msg = okHttpException.getEmsg().toString();
                if (msg.contains("java.net.ConnectException")) {
                    CommonUtil.showToast(getActivity(), "无法连接服务器，请检查您的网络");
                }else{
                    CommonUtil.showToast(getActivity(), msg);
                }
            }
        }).requestWeb(url, clazz, list, status, page + "",(String) CommonUtil.readData(getActivity(), Constant.TOKEN,Constant.STRING));
    }

    /**
     * 按钮点击的相关参数请求
     *
     * @param type
     */
    @Override
    public void buttonClick(final String type,int position,String reason) {
        orderNeedDelete = list_order.get(position);
        dialogWeb.show();
        String url = WebUrl.REQUEST_BUTTON;
        Class<?> clazz = CommonBean.class;
        final List<String> list = new ArrayList<>();
        list.add("token");
        list.add("id");
        list.add("type");
        if (type.equals("cancel")){
            list.add("reason");
        }
        new RequestWebInfo(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                dialogWeb.dismiss();
                CommonBean commonBean = (CommonBean) responseObj;
                CommonUtil.showToast(context,commonBean.getMessage().getResultMessage());
                if (type.equals("cancel") || type.equals("handle") || type.equals("re_notify_deliveryer_collect")
                        || type.equals("end") || type.equals("refund_status")){
                    //取消，需要remove
                    if (list_order.contains(orderNeedDelete)){
                        list_order.remove(orderNeedDelete);
                        waitOrderAdapter.notifyDataSetChanged();
                    }
                }
                if (type.equals("refund_handle") || type.equals("refund_query")){
                    refreshLayout.autoRefresh();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                dialogWeb.dismiss();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                OkHttpException okHttpException = (OkHttpException) reasonObj;
                String msg = okHttpException.getEmsg().toString();
                if (msg.contains("java.net.ConnectException")) {
                    CommonUtil.showToast(getActivity(), "无法连接服务器，请检查您的网络");
                }else{
                    CommonUtil.showToast(getActivity(), msg);
                }
            }
        }).requestWeb(url, clazz, list, (String) CommonUtil.readData(getActivity(), Constant.TOKEN,Constant.STRING),list_order.get(position).getId(),type,reason);
    }

    @Override
    public void cancleJump(int position) {
        Intent intent = new Intent(context, CancelReasonActivity.class);
        intent.putExtra("position",position);
        startActivityForResult(intent,CANCEL_REASON);
    }

    /**
     * 调度
     * @param position
     */
    @Override
    public void diaodu(final int position) {
        orderNeedDelete = list_order.get(position);
        dialogWeb.show();
        String url = WebUrl.DIAPATCH;
        Class<?> clazz = DispatchBean.class;
        List<String> list = new ArrayList<>();
        list.add("id");
        list.add("token");
        new RequestWebInfo(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                dialogWeb.dismiss();
                String json = RequestWebInfo.jsonInfo;
                DispatchBean dispatchBean = (DispatchBean) responseObj;
                List<DeliveryerBean> listDeliveryer = new ArrayList<>();
                for (int i=0;i<dispatchBean.getMessage().getData().getDeliveryers().size();i++){
                    DeliveryerBean deliveryerBean = new DeliveryerBean();
                    deliveryerBean.setName(dispatchBean.getMessage().getData().getDeliveryers().get(i).getTitle());
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getDeliveryers().get(i).getLocation_x())) {
                        deliveryerBean.setLatitude(Double.parseDouble(dispatchBean.getMessage().getData().getDeliveryers().get(i).getLocation_x()));
                    }else{
                        continue;
                    }
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getDeliveryers().get(i).getLocation_y())) {
                        deliveryerBean.setLongitude(Double.parseDouble(dispatchBean.getMessage().getData().getDeliveryers().get(i).getLocation_y()));
                    }else{
                        continue;
                    }
                    deliveryerBean.setOrder_errander_num(dispatchBean.getMessage().getData().getDeliveryers().get(i).getOrder_errander_num());
                    deliveryerBean.setOrder_takeout_num(dispatchBean.getMessage().getData().getDeliveryers().get(i).getOrder_takeout_num());
                    deliveryerBean.setId(dispatchBean.getMessage().getData().getDeliveryers().get(i).getId());
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getLocation_x())) {
                        deliveryerBean.setLatitudeCustomer(Double.parseDouble(dispatchBean.getMessage().getData().getLocation_x()));
                    }else{
                        continue;
                    }
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getLocation_y())) {
                        deliveryerBean.setLongitudeCustomer(Double.parseDouble(dispatchBean.getMessage().getData().getLocation_y()));
                    }else{
                        continue;
                    }
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getStore().getLocation_x())) {
                        deliveryerBean.setLatitudeShop(Double.parseDouble(dispatchBean.getMessage().getData().getStore().getLocation_x()));
                    }else{
                        continue;
                    }
                    if (!NullUtil.isStringEmpty(dispatchBean.getMessage().getData().getStore().getLocation_y())) {
                        deliveryerBean.setLongitudeShop(Double.parseDouble(dispatchBean.getMessage().getData().getStore().getLocation_y()));
                    }else{
                        continue;
                    }
                    listDeliveryer.add(deliveryerBean);
                }
                //跳转到地图页面，然后显示相关内容
                Intent intent = new Intent(getActivity(), DispatchMapActivity.class);
                intent.putExtra("info",(Serializable) listDeliveryer);
                intent.putExtra("orderId",list_order.get(position).getId());
                startActivityForResult(intent,JUMP_MAP);
            }

            @Override
            public void onFailure(Object reasonObj) {
                dialogWeb.dismiss();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                OkHttpException okHttpException = (OkHttpException) reasonObj;
                String msg = okHttpException.getEmsg().toString();
                if (msg.contains("java.net.ConnectException")) {
                    CommonUtil.showToast(getActivity(), "无法连接服务器，请检查您的网络");
                }else{
                    CommonUtil.showToast(getActivity(), msg);
                }
            }
        }).requestWeb(url, clazz, list, list_order.get(position).getId(),(String) CommonUtil.readData(getActivity(), Constant.TOKEN,Constant.STRING));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == homeActivity.RESULT_OK){
            switch (requestCode){
                case CANCEL_REASON:
                    String reason = data.getStringExtra("reason");
                    int position = data.getIntExtra("position",-1);
                    if (position != -1) {
                        buttonClick("cancel", position, reason);
                    }else{
                        CommonUtil.showToast(context,"取消原因选择失败");
                    }
                    break;
                case REFRESH_LAYOUT:
                    refreshLayout.autoRefresh();
                    break;
                case JUMP_MAP:
                    if (status.equals("2") || status.equals("3")){
                        if (list_order.contains(orderNeedDelete)) {
                            list_order.remove(orderNeedDelete);
                            waitOrderAdapter.notifyDataSetChanged();
                        }
                    }else if (status.equals("4")){
                        refreshLayout.autoRefresh();
                    }
                    break;
            }
        }
    }

    /**
     * 外部调用的数据刷新
     */
    public void reFreshData(){
        refreshLayout.autoRefresh();
    }
}
